package com.jsmile.cloud.tradecenter.order.factory;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

import com.jsmile.cloud.accountcenter.api.feign.MemberServiceApi;
import com.jsmile.cloud.accountcenter.api.req.ReqMemberDetial;
import com.jsmile.cloud.accountcenter.api.res.ResMember;
import com.jsmile.cloud.goodscenter.api.constants.GoodsConstants;
import com.jsmile.cloud.goodscenter.api.feign.SkuServiceApi;
import com.jsmile.cloud.goodscenter.api.req.spu.ReqSkuCheck;
import com.jsmile.cloud.goodscenter.api.res.ResSku;
import com.jsmile.cloud.tradecenter.api.exception.TradeException;
import com.jsmile.cloud.tradecenter.api.req.ReqOrderCreate;
import com.jsmile.mall.api.JSmileResult;
import com.jsmile.mall.cache.kit.SpringKit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单检查并返回对应的数据
 */
@Slf4j
@Data
public class OrderCheckKit {

    private ResMember resMember;
    private List<ResSku> skuList;
    private ReqOrderCreate reqOrderCreate;
    private Queue<Long> orderNos;
    // 是否发送订单创建事件（订单预览不发）
    private Boolean hasEvent = false;

    public OrderCheckKit(ReqOrderCreate reqOrderCreate) {
        this.reqOrderCreate = reqOrderCreate;
    }

    public static OrderCheckKit me(ReqOrderCreate reqOrderCreate) {
        return new OrderCheckKit(reqOrderCreate);
    }

    // 检查会员信息
    public OrderCheckKit checkMember() {
        JSmileResult<ResMember> memberJSmileResult = SpringKit.getBean(MemberServiceApi.class).getMember(ReqMemberDetial.builder().userId(reqOrderCreate.getCurUserId()).build());
        if (!memberJSmileResult.getResSuccess()) {
            throw new TradeException(memberJSmileResult.getResCode(), memberJSmileResult.getResMsg(), null);
        }
        this.resMember = memberJSmileResult.getResData();
        return this;
    }

    // 获取商品信息
    public OrderCheckKit checkGoods() {
        JSmileResult<List<ResSku>> jSmileResult = SpringKit.getBean(SkuServiceApi.class).skuCheck(ReqSkuCheck.builder().skuList(reqOrderCreate.getSkuList().stream().map(x -> {
            ReqSkuCheck.SkuCheck reqSkuCheck = BeanUtil.toBean(x, ReqSkuCheck.SkuCheck.class);
            return reqSkuCheck;
        }).collect(Collectors.toList())).build());
        if (!jSmileResult.getResSuccess()) {
            throw new TradeException(jSmileResult.getResCode(), jSmileResult.getResMsg(), null);
        }
        this.skuList = jSmileResult.getResData();
        return this;
    }

    // 生成订单编号
    public OrderCheckKit genOrderNos(int n) {
        Queue<Long> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            queue.add(IdUtil.getSnowflake(GoodsConstants.SNOWFLAKE.workerId, i).nextId());
        }
        this.setOrderNos(queue);
        return this;
    }
}
